// menu菜单相关处理方法
import { useRoute, RouteRecordRaw } from 'vue-router';
import useRouterHelp from '@/hooks/useRouterHelp';
import { useMenuStore } from '@/store/modules/menu';
import {routeMenuConfig} from '@/setting/route-menu-config';

export default function useMenu(options: any = {isMenuChildrenOnlyIndex: false}) {
    const { isMenuChildrenOnlyIndex } = options;
    // isMenuChildrenOnlyIndex 子菜单是否过滤掉只剩下index子路由对应菜单

    const {generateNestedRoutes} = useRouterHelp();
    const menuStore = useMenuStore();

    const generateAutoMenus = () => {
        const nextedRoutes = generateNestedRoutes();
        const menus =  generateMenuFromRoutes(nextedRoutes);
        menuStore.setMenus(menus);
        return menus;
    }

    /**
 * 将路由配置转换为Ant Design Vue菜单配置
 * @param routes 路由配置数组
 * @param parentPath 父级路径（内部使用）
 * @returns 生成的菜单配置数组
 */
 function generateMenuFromRoutes(
    routes: RouteRecordRaw[],
    parentPath: string = ''
  ): MenuItem[] {
    return routes
      .filter(route => {
        // 路由菜单是否展示隐藏
        const isHidden = !!routeMenuConfig[route.name]?.hidden;
        return route.name && !route.meta?.hidden && !isHidden;
      })
      .map(route => {
        // 处理完整路径
        const fullPath = route.path.startsWith('/')
          ? route.path
          : `${parentPath}/${route.path}`.replace(/\/+/g, '/');

        const label = routeMenuConfig[route.name]?.label ? routeMenuConfig[route.name]?.label : String(route.name);
        const icon = routeMenuConfig[route.name]?.icon;
        // 构建基础菜单项【a-menu组件菜单节点对象配置】
        const menuItem: MenuItem = {
          id: fullPath,
          key: fullPath,
          title: label,
          label: label,
          icon: icon,
          isParent: !!route?.meta?.isParent,
        }
  
        // 处理图标
        if (route.meta?.icon) {
          menuItem.icon = route.meta.icon
        }
  
        // 递归处理子路由
        if (route.children?.length) {
          menuItem.children = generateMenuFromRoutes(route.children, fullPath)
          
          // 如果没有子菜单项，则移除children属性
          if (menuItem.children.length === 0) {
            delete menuItem.children
          } else {
            // 如果子菜单只有一项且路径相同，则合并
            if (menuItem.children.length === 1 && menuItem.children[0].path === fullPath) {
              const singleChild: any = menuItem.children[0]
              menuItem.key = singleChild.key
              menuItem.path = singleChild.path
              if (singleChild.icon) menuItem.icon = singleChild.icon
              delete menuItem.children
            }
          }
        }
  
        return menuItem
      })
  }

    // 查找菜单节点路径函数【面包屑组件数据】
    const findMenuPath = (
        tree: MenuItem[],
        targetId: string,
        path: MenuItem[] = []
    ): MenuItem[] | null => {
        for (const node of tree) {
            const currentPath = [...path, node]
            if (node.id === targetId) {
                return currentPath
            }
            if (node.children) {
                const found = findMenuPath(node.children, targetId, currentPath)
                if (found) return found
            }
        }
        return null
    }
    // 通过当前路由获取当前菜单
    const getCurrentMenuByRoute = (menuList, path = '') => {
        const route = useRoute();
        const targetPath = path || route?.path;
        function findMenu(menus) {
            for (const menu of menus) {
                if (targetPath === menu?.key) {
                    return menu;
                }
                if (menu.children) {
                    const target = findMenu(menu.children);
                    if(target) return target;
                }
            }
            return null;
        }
        return findMenu(menuList);
    }
 
    return { generateAutoMenus, findMenuPath, getCurrentMenuByRoute }
}